package cn.zy.gvs.v1.controller;

import cn.hutool.core.date.DateUtil;
import cn.zy.gvs.v1.core.common.domain.AjaxResult;
import cn.zy.gvs.v1.model.SysFile;
import cn.zy.gvs.v1.model.vo.SysFileVo;
import cn.zy.gvs.v1.service.ISysFileService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Yann
 */
@RestController
@RequestMapping("${gvs.apiPrefix}/file")
@RequiredArgsConstructor
public class FileController {

    private final ISysFileService sysFileService;

    private final FileStorageService fileStorageService;

    /**
     * 获取文件列表 [根据类型]
     * 0: 系统自动默认缓存图片
     * 1: 上传的素材图片
     */
    @GetMapping("/list")
    public AjaxResult getFileList(@RequestParam(value = "fileUse") String fileUse) {
        List<SysFile> list = sysFileService.list(new LambdaQueryWrapper<SysFile>()
                .eq(SysFile::getFileUse, fileUse));
        return AjaxResult.success(list);
    }

    /**
     * 上传素材文件
     * @param object 文件流
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestBody MultipartFile object) throws IOException {

        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        FileInfo fileInfo = fileStorageService.of(object)
                // 增加日期目录
                .setPath("material/" + format + "/")
                // 文件用途
                .putAttr("fileUse", "1")
                // 开始上传
                .upload();
        SysFileVo fileVo = new SysFileVo();
        fileVo.setFileName(fileInfo.getOriginalFilename());
        fileVo.setFileUrl(fileInfo.getUrl());
        fileVo.setId(fileInfo.getId());
        return AjaxResult.success(fileVo);
    }

    /**
     * 删除文件
     * @param id 主键
     */
    @DeleteMapping("/del/{id}")
    public AjaxResult deleteFile(@PathVariable String id) {
        SysFile file = sysFileService.getById(id);
//        boolean b = sysFileService.removeById(id);
        fileStorageService.delete(file.getUrl());
        return AjaxResult.success();
    }
}
